import { Request, Response } from 'express';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { UserModel } from '../models/User';
import { ConfigModel } from '../models/Config';
import { NginxUtil } from '../utils/nginx.util';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

interface SetupRequest {
  username: string;
  password: string;
  nginxConfig?: {
    nginxExec?: string;
    nginxCwd?: string;
    nginxConfDir?: string;
    isDockerized?: boolean;
    dockerContainerName?: string;
    dockerHostPath?: string;
    dockerContainerPath?: string;
  };
}

export class AuthController {
  // 检查系统状态
  static async checkSystemStatus(req: Request, res: Response) {
    try {
      const hasAdmin = await UserModel.hasAdmin();
      res.json({ 
        needsSetup: !hasAdmin,
        message: hasAdmin ? '系统已初始化' : '需要设置管理员账号'
      });
    } catch (error) {
      res.status(500).json({ message: '检查系统状态失败' });
    }
  }

  // 初始化管理员账号
  static async setupAdmin(req: Request<{}, {}, SetupRequest>, res: Response) {
    try {
      const hasAdmin = await UserModel.hasAdmin();
      if (hasAdmin) {
        return res.status(400).json({ message: '管理员账号已存在' });
      }

      const { username, password, nginxConfig } = req.body;
      if (!username || !password) {
        return res.status(400).json({ message: '用户名和密码不能为空' });
      }

      // 保存 Nginx 配置
      if (nginxConfig) {
        // 如果是 Docker 部署，验证必要的字段
        if (nginxConfig.isDockerized) {
          if (!nginxConfig.dockerContainerName || !nginxConfig.dockerHostPath || !nginxConfig.dockerContainerPath) {
            return res.status(400).json({ message: 'Docker 部署模式下需要提供容器名称、宿主机路径和容器内路径' });
          }
        }

        await ConfigModel.create(nginxConfig);

        // 更新环境变量
        if (nginxConfig.nginxExec) {
          process.env.NGINX_EXEC = nginxConfig.nginxExec;
        }
        if (nginxConfig.nginxCwd) {
          process.env.NGINX_CWD = nginxConfig.nginxCwd;
        }
        if (nginxConfig.nginxConfDir) {
          process.env.NGINX_CONF_DIR = nginxConfig.nginxConfDir;
        }
        await NginxUtil.updateEnv();
      }

      const userId = await UserModel.create({
        username,
        password,
        role: 'admin'
      });

      const user = await UserModel.findByUsername(username);
      if (!user) {
        return res.status(500).json({ message: '创建管理员账号失败' });
      }

      const token = jwt.sign(
        { id: user.id, username: user.username, role: user.role },
        JWT_SECRET,
        { expiresIn: '24h' }
      );

      res.json({
        message: '管理员账号创建成功',
        token,
        user: {
          id: user.id,
          username: user.username,
          role: user.role
        }
      });
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  // 用户登录
  static async login(req: Request, res: Response) {
    try {
      const { username, password } = req.body;

      const user = await UserModel.findByUsername(username);
      if (!user) {
        return res.status(401).json({ message: '用户名或密码错误' });
      }

      const isValid = await UserModel.verifyPassword(user, password);
      if (!isValid) {
        return res.status(401).json({ message: '用户名或密码错误' });
      }

      const token = jwt.sign(
        { id: user.id, username: user.username, role: user.role },
        JWT_SECRET,
        { expiresIn: '24h' }
      );

      res.json({
        token,
        user: {
          id: user.id,
          username: user.username,
          role: user.role
        }
      });
    } catch (error) {
      res.status(500).json({ message: '登录失败' });
    }
  }

  // 获取当前用户信息
  static async getCurrentUser(req: Request, res: Response) {
    try {
      if (!req.user?.id) {
        return res.status(401).json({ message: '未授权' });
      }

      const user = await UserModel.findByUsername(req.user.username);
      if (!user) {
        return res.status(404).json({ message: '用户不存在' });
      }

      res.json({
        user: {
          id: user.id,
          username: user.username,
          role: user.role
        }
      });
    } catch (error) {
      res.status(500).json({ message: '服务器错误' });
    }
  }
} 